﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebSocketClient;

namespace WinFormsClient
{
    public partial class Form1 : Form
    {
        WSocketClient client = null;
        public Form1()
        {
            InitializeComponent();


        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            //自定义的地址参数 可以根据地址参数来区分客户端 /lcj控制台
            if (txtBoxIP.Text.Trim() == "")
            {
                MessageBox.Show("服务器地址不能为空！");
                return;
            }
            client = new WSocketClient(txtBoxIP.Text);
            MessageReceived();
            //开始链接
            client.Start();
            SetText("启动与服务器连接");

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            //客户端发送消息到服务端
            // if (txtBoxInput.Text.Trim() != "")
            //  {
            //      client.SendMessage(txtBoxInput.Text);
            //  }
            string inputMsg = txtBoxInput.Text.ToString();
            if (string.IsNullOrEmpty(inputMsg))
                MessageBox.Show("小调皮,空值不让传！");
            client.SendMessage(inputMsg);
            MessageReceived();

        }

        /// <summary>
        /// 服务端返回的消息
        /// </summary>
        private void MessageReceived()
        {
            // Control.CheckForIllegalCrossThreadCalls = false; //第一种方法解决：线程间操作无效: 从不是创建控件“txtBoxRec”的线程访问它。可能还会出现死锁
            //注册消息接收事件，接收服务端发送的数据
            client.MessageReceived += (data) =>
            {
                // txtBoxRec.Text += data;
                SetText(data);
            };
        }


        //第二种方法解决（最安全的）线程间操作无效: 从不是创建控件“txtBoxRec”的线程访问它
        delegate void SetTextHander(string recvStr);//带参数

        private void SetText(string recvStr)
        {
            if (txtBoxRec.InvokeRequired)//判断是否是线程在访问该控件
            {
                SetTextHander set = new SetTextHander(SetText);//委托的方法参数应和SetText一致
                txtBoxRec.Invoke(set, recvStr); //委托自身，递归委托，直到不是以invoke方式去访问控件
            }
            else
            {
                txtBoxRec.AppendText(recvStr + "\r\n");
            }
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Dispose();
                SetText("已断开服务器");
            }

        }

        private void txtBoxIP_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
